var saveButton = $('a.save-button');

var RegionModel = function(id, name) {

	var self = this;

	self.id = id;

	self.region = name;

};

var LocalityGroupModel = function(regions, localitygroups) {

	var self = this;

	self.ids = [];

	self.regions = null;

	self.initializeRegions = function() {
		var r = [];

		for (i = 0; i < regions.length; i++) {
			var region = regions[i];
			var regionModel = new RegionModel(region.Id, region.Region);
			r.push(regionModel);
		}

		self.regions = ko.observableArray(r);		
	};

	self.initializeRegions();

	self.isValid = function() {
		var valid = true;
		var items = ko.toJS(self.localityGroups);
		
		if (items != undefined) {
			if (items.length != undefined) {
				for (i = 0; i < items.length; i++) {
					var item = items[i];
					valid = valid && ($.trim(item.LocalityGroup) != '');
					if (!valid) break;
					else {
						valid = valid && (item.Region != '') && (item.Region != 'Choose one...');
						if (!valid) break;
					}
				}	
			}	
		}
		
		return valid;
	};

	self.localityGroups = ko.observableArray(ko.utils.arrayMap(localitygroups, function(localitygroup) {
		self.ids.push(localitygroup.Id);

		var viewModel = { 
							Id : localitygroup.Id, 
							Region : localitygroup.RegionId,
							LocalityGroup : localitygroup.LocalityGroup,
							Description : localitygroup.Description,
							RowState : 'unchanged'
						};

		viewModel.Region = ko.observable(localitygroup.RegionId).extend( { modelUpdated : viewModel, validator: { 'saveButton': saveButton, references: ko.toJS(self.regions), referenceKey: 'id', saveButtonEnable: function() { return self.isValid(); } } } );
		viewModel.LocalityGroup = ko.observable(localitygroup.LocalityGroup).extend( { modelUpdated : viewModel, validator: { 'saveButton': saveButton, saveButtonEnable: function() { return self.isValid(); } } } );
		viewModel.Description = ko.observable(localitygroup.Description).extend( { modelUpdated : viewModel } );

		return viewModel;
	}));

	self.deletedItems = [];

	self.acceptChanges = function(viewUpdates) {
		ko.utils.arrayForEach(self.localityGroups(), function(localitygroup) {
			localitygroup.RowState = 'unchanged';

			if (viewUpdates != null &&
				viewUpdates != undefined) {
				for (i = 0; i < viewUpdates.length; i++) {
					var viewUpdate = viewUpdates[i];
					if (localitygroup.Id == viewUpdate.Id) {
						localitygroup.Id = viewUpdate.GeneratedId;
						break;
					}
				}
			}
		});
	};

	self.add = function() {
		var id = 1;

		if (self.ids.length > 0) {
			var max = Math.max.apply(Math, self.ids);
			id = max + 1;
		}

		self.ids.push(id);

		var viewModel = {
							Id : id,
							Region: 0,
							LocalityGroup: '',
							Description: '',
							RowState: 'added'
						};

		viewModel.Region = ko.observable(0).extend( { modelUpdated : viewModel, validator: { 'saveButton': saveButton, references: ko.toJS(self.regions), referenceKey: 'id', saveButtonEnable: function() { return self.isValid(); } } } );
		viewModel.LocalityGroup = ko.observable('').extend( { modelUpdated : viewModel, validator: { 'saveButton': saveButton, saveButtonEnable: function() { return self.isValid(); } } } );
		viewModel.Description = ko.observable('').extend( { modelUpdated : viewModel } );
		
		self.localityGroups.push(viewModel);

		setRemoveLocalityGroupToolTips();

		var table = $('.locality-groups-table');
		table.floatThead('reflow');

		if (!saveButton.hasClass('disabled')) saveButton.addClass('disabled');
		
		var rowRegionInput = $('tr[data-id="' + id + '"] td .form-group select');
		rowRegionInput.focus();
	};

	self.getChanges = function() {
		var updates = [];
		var items = ko.toJS(self.localityGroups);

		for (i = 0; i < items.length; i++) {
			var item = items[i];
			if (item.RowState != 'unchanged') updates.push( { Id: item.Id, Region: item.Region, LocalityGroup: item.LocalityGroup, Description: item.Description, RowState: item.RowState } );
		}

		for (i = 0; i < self.deletedItems.length; i++) {
			var item = self.deletedItems[i];
			updates.push( { Id: item.Id, Region: 0, LocalityGroup: '', Description: '', RowState: 'deleted' } );	
		}

		return updates;
	}

	self.remove = function(localitygroup) {
		unsetRemoveLocalityGroupToolTips();
		
		if (localitygroup.RowState != 'added') {
			localitygroup.RowState = 'deleted';
			self.deletedItems.push(localitygroup);
		}
		
		self.localityGroups.remove(localitygroup);
		setRemoveLocalityGroupToolTips();

		if (self.isValid())  saveButton.removeClass('disabled');
		else {
			if (!saveButton.hasClass('disabled')) saveButton.addClass('disabled');
		}
	};

	self.save = function() {
		if (saveButton.hasClass('disabled')) return;
		else saveButton.addClass('disabled');

		saveButton.button('loading');

		var updates = self.getChanges();
		var withUpdates = false;

		if (updates != null) withUpdates = (updates.length > 0);

		if (withUpdates) {
			$.ajax({
			    type: 'POST',
			    url: app.baseUrl() + 'index.php/references/update',
			    data: { 'data' : JSON.stringify(updates) },
			    dataType: 'json'
			}).done(function(response) {
				if (response != null) {
					try {
						console.info(response);
					}
					catch (ex) {

					}

					if (response.saved) {
						var viewUpdates = null;

						if (response.viewUpdates != null &&
							response.viewUpdates != undefined) viewUpdates = response.viewUpdates;
						
						self.acceptChanges(viewUpdates);
						
						infoGritter({
							title: 'Record Update',
							text: 'Applied updates has been saved.'
						});
					}
					else {
						var message = 'Applied updates were not saved into the database.';

						if (response.message != undefined &&
							response.message != null) {
							if (response.message.trim() != '') message = response.message;
						}

						warningGritter({
							title: 'Record Update',
							text: message
						});
					}
				}
			}).fail(function(response) {
				try {
					console.error(response);
				}
				catch (ex) {

				}

				errorGritter({
					title: 'Oooops',
					text: 'Something went wrong while applying the updates into the server.'
				});
			}).always(function() {
				saveButton.removeClass('disabled');
				saveButton.button('reset');
			});
		}
		else {
			saveButton.removeClass('disabled');
			saveButton.button('reset');
		}
	};
}

var setRemoveLocalityGroupToolTips = function() {
	unsetRemoveLocalityGroupToolTips();
	var removeLinks = $('a.remove-record');
	removeLinks.tooltip( { 
			'title' : 'Remove current line-item from the list.',
			'trigger' : 'hover',
			'container' : 'body' 
		} 
	);
};

var unsetRemoveLocalityGroupToolTips = function() {
	var removeLinks = $('a.remove-record');
	removeLinks.tooltip('destroy');
};

$(document).ready(function() {
	var displaySection = $('.table-container');
	app.loader({ container: displaySection });

	$.post(app.baseUrl() + 'index.php/references/regions').done(function(regionData) {
		var regions = null;

		try {
			regions = JSON.parse(regionData);
		}
		catch(ex) {

		}

		if (regions != null) {
			$.post(app.baseUrl() + 'index.php/references/localityGroups').done(function(localityGroupData) {
				var localityGroups = null;

				try {
					localityGroups = JSON.parse(localityGroupData);
				}
				catch (ex) {

				}

				if (localityGroups != null)  {
					ko.applyBindings(new LocalityGroupModel(regions, localityGroups));
					setRemoveLocalityGroupToolTips();

					var table = $('.locality-groups-table');
					table.floatThead({
					    scrollContainer: function(refTable){
							return refTable.closest('.table-container');
						}
					});
				}
			}).fail(function(response) {
				try {
					console.error(response);
				}
				catch (ex) {

				}

				errorGritter({
					title: 'Oooops',
					text: 'Something went wrong while loading the data to be displayed. Please try again.'
				});
			}).always(function() {
				app.loader('hide');
			});
		}
	}).fail(function(response) {
		try {
			console.error(response);
		}
		catch (ex) {

		}

		errorGritter({
			title: 'Oooops',
			text: 'Something went wrong while loading some references. Please try again.'
		});

		app.loader('hide');
	}).always(function() {

	});
});